package com.hyl.springbootredis.controller;

import com.hyl.springbootredis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;

import java.net.http.HttpRequest;
import java.util.concurrent.TimeUnit;

/**
 * LoginController
 *
 * @author hyl
 * @date 2025-01-13
 */
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public String login(String username, String password){
        //1.根据用户名，获取用户信息
        User user = new User();
        user.setUsername(username);
        user.setPassword("111");
        if(user == null){
            return "用户不存在";
        }
        //2.用户存在，判断用户的状态=》锁定
        String lockkey = "lock.login_user_lock_"+user.getId();
        if(stringRedisTemplate.opsForValue().get(lockkey).equals("1")){
            return "用户锁定";
        }
        //3.判断用的密码=》错误
        //4.密码错误
        if (!user.getPassword().equals(password)) {
            String key = "lock.login_user_count_"+user.getId();
            String count = stringRedisTemplate.opsForValue().get(key);
            int cnt = 1;  //第一次错
            if(count != null){ //说明已经错过>1
                cnt = Integer.parseInt(count)+1;
            }
            //4.1 错误次数 +1
            stringRedisTemplate.opsForValue().set(key, String.valueOf(cnt),2, TimeUnit.HOURS); //2小时
            //4.2 超过错误上限 =》锁定
            if(cnt > 5){

                stringRedisTemplate.opsForValue().set(lockkey, "1",24, TimeUnit.HOURS); //一天
                stringRedisTemplate.delete(key);
                return "密码错误次数超过上限，账号锁定24小时";
            }
            return "密码错误"+cnt+"次";

        }

        //session.setAttribute("loginUser",user);

        return "登入成功";
    }

    public String getCode(String phone){
        String code = "lock.login_user_code_"+phone;
        String tmp = "12456";
        stringRedisTemplate.opsForValue().set(code, tmp, 1, TimeUnit.MINUTES);
        return tmp;
    }
}
